//
//  MyHomeViewModel.swift
//  DaRings
//
//  Created by 易先生 on 2022/10/27.
//

import UIKit
import RxSwift
import RxCocoa
import MYModule
import CRPSmartRing


class MyHomeViewModel: ViewModel, ViewModelType{

    public var profileItems: [MyHomeItem] = MyHomeCellType.allCases.map({ MyHomeItem(type: $0) })
 
    public var showItems: [MyHomeItem] {
        
        var allItems = profileItems
        let diviceInfo = DeviceInfo.current()
        if diviceInfo.isBind == false {
           allItems = allItems.filter { $0.type != .firmware }
        }
        return allItems
    }
    
    
    struct Input {
        let viewWillAppear: ControlEvent<Bool>
        let advClick: Driver<Void>
    }
    
    struct Output {
        let items: BehaviorRelay<[MyHomeItem]>
        let hasDevice: Driver<Bool>
        let deviceName: Driver<String>
        let macAddress: Driver<String>
        let deviceState: Driver<String>
        let batteryString: Driver<String>
        let batteryImgHidden: Driver<Bool>
        let batteryPercent: Driver<Double>
        let batteryChargImgHidden: Driver<Bool>
        let devicePreviewImage: Driver<(url: URL?, placeholdImage: UIImage?)>
        let OTABrage: Driver<Bool>
    }
    
    
    public func reloadData() {
        
        
        
    }
    
    public func transform(input: Input) -> Output {
        
        let items = BehaviorRelay<[MyHomeItem]>(value: [])
        let hasDevice = PublishSubject<Bool>()
        let deviceName = PublishSubject<String>()
        let macAddress = PublishSubject<String>()
        let deviceState = PublishSubject<String>()
        let batteryString = PublishSubject<String>()
        let batteryPercent = BehaviorRelay<Double>(value: 0)
        let batteryImgHidden = BehaviorRelay<Bool>(value: true)
        let batteryChargImgHidden = BehaviorRelay<Bool>(value: true)
        let devicePreviewImage = PublishSubject<(url: URL?, placeholdImage: UIImage?)>()
        let OTABrage = BehaviorRelay<Bool>(value: false)
        
        /// 更新电量信息
        func batteryInfo(value: Int) {
            if BluetoothManager.shared.bluetoothState == .poweredOff || BluetoothManager.shared.deviceState != .connected {
                batteryPercent.accept(0)
                batteryString.onNext("--%")
                batteryImgHidden.accept(true)
                batteryChargImgHidden.accept(true)
                return
            }
            if value <= 100 {
                let str = "\(value)%"
                batteryPercent.accept(Double(value) / 100.0)
                batteryString.onNext(str)
                batteryImgHidden.accept(false)
                batteryChargImgHidden.accept(true)
            } else {
                batteryPercent.accept(0)
                batteryString.onNext("")
                batteryImgHidden.accept(true)
                batteryChargImgHidden.accept(false)
            }
            
        }
        
        items.accept(showItems)
        
        
        func deviceChanged() {
            
            let deviceModel = DeviceInfo.current()
           
            // 未绑定设备
            if deviceModel.isBind == false {
                hasDevice.onNext(false)
                return
            }
            
            hasDevice.onNext(true)
            
            /// 获取设备信息
            if let tmpName = deviceModel.localName {
                deviceName.onNext(tmpName)
            }
            
            if let mac = deviceModel.adress {
                macAddress.onNext(mac)
            }
            
            // 获取设备状态
            if BluetoothManager.shared.bluetoothState == .poweredOff {
                deviceState.onNext("ble_disable".language)
                batteryString.onNext("--%")
                batteryImgHidden.accept(true)
            } else {
                if BluetoothManager.shared.deviceState == .connected {
                    
                    deviceState.onNext("ble_connected".language)
                } else {
                    deviceState.onNext("ble_connecting".language)
                    batteryString.onNext("--%")
                    batteryImgHidden.accept(true)
                }
            }
            /// 获取预览图
            var tmpImage = UIImage(named: "ic_ring")
            var imageURL: URL?
            if let info = deviceModel.info, let url = info.imageURL {
                
                tmpImage = UIImage(named: info.color.imageName)
                imageURL = URL(string: url)
                    
            }
            
            devicePreviewImage.onNext((imageURL, tmpImage))
            
            let currentBattery = BluetoothManager.shared.currentBattery ?? 0
            /// 电量信息
            batteryInfo(value: currentBattery)
            
        }
        
        /// 固件升级cell
        if let firmwareItem = profileItems.filter({ $0.type == .firmware }).first {
            
            OTABrage.map {[weak self] in
                
                guard let self = self else { return [] }
                firmwareItem.brage = $0
                
                return self.showItems
                
            }.bind(to: items).disposed(by: rx.disposeBag)
            
            
            hasDevice.map { [weak self] in
                
                guard let self = self else { return [] }
                
                firmwareItem.isHidden = !$0
                
                return self.showItems
                
            }.bind(to: items).disposed(by: rx.disposeBag)
            
        }
        
        
        input.viewWillAppear.subscribe(onNext: {[weak self] _ in
            
                deviceChanged()
            
                self?.OTARequest(OTABrageRelay: OTABrage)
            
        }).disposed(by: rx.disposeBag)
        
        /// 获取设备电量
        NotificationCenter.default.rx.notification(.kBatteryNotification).take(until: self.rx.deallocated).subscribe(onNext: {notification in
            
            // 获取设备状体和电量
            guard let dict = notification.userInfo as? [String: Any], let value = dict["result"] as? Int else { return }
         
            batteryInfo(value: value)
               
            
        }).disposed(by: rx.disposeBag)
        

        NotificationCenter.default.rx.notification(Notification.Name.kBluetoothStateNotification)
            .take(until: self.rx.deallocated)
            .subscribe(onNext:{notification in

            guard let result = notification.userInfo as? [String: Any] else { return}
            guard let state = result["result"] as? CRPBluetoothState else { return }
            switch state{
            case .poweredOff:
                deviceState.onNext("ble_disable".language)
                batteryString.onNext("--%")
                batteryImgHidden.accept(true)
            default:
                deviceState.onNext("ble_connecting".language)
            }
          

        }).disposed(by: rx.disposeBag)
        
        NotificationCenter.default.rx.notification(Notification.Name.kDeviceStateNotification).take(until: self.rx.deallocated).subscribe(onNext:{ [weak self]notification in
            guard let self = self else { return }
            guard let result = notification.userInfo as? [String: Any] else { return}
            guard let state = result["result"] as? CRPState else { return }
            switch state{
            case .connected:
                
                deviceChanged()
                
                deviceState.onNext("ble_connected".language)
                
                
            case .disconnected:
                deviceState.onNext("ble_connecting".language)
                batteryString.onNext("--%")
                batteryImgHidden.accept(true)
            case .connecting:
                deviceState.onNext("ble_connecting".language)
                batteryString.onNext("--%")
                batteryImgHidden.accept(true)
            default:
                deviceState.onNext("ble_connecting".language)
                batteryString.onNext("--%")
                batteryImgHidden.accept(true)
            }
            log.debug(self.showItems.count)
            items.accept(self.showItems)

        }).disposed(by: rx.disposeBag)
        
        return Output(items: items,
                      hasDevice: hasDevice.asDriverOnErrorJustComplete(),
                      deviceName: deviceName.asDriverOnErrorJustComplete(),
                      macAddress: macAddress.asDriverOnErrorJustComplete(),
                      deviceState: deviceState.asDriverOnErrorJustComplete(),
                      batteryString: batteryString.asDriverOnErrorJustComplete(),
                      batteryImgHidden: batteryImgHidden.asDriverOnErrorJustComplete(),
                      batteryPercent: batteryPercent.asDriverOnErrorJustComplete(),
                      batteryChargImgHidden: batteryChargImgHidden.asDriverOnErrorJustComplete(),
                      devicePreviewImage: devicePreviewImage.asDriverOnErrorJustComplete(),
                      OTABrage: OTABrage.asDriverOnErrorJustComplete()
        )
    }
    
}

extension MyHomeViewModel {
    
    /// OTA 升级接口
    func OTARequest(OTABrageRelay: BehaviorRelay<Bool>) {
        
        let deviceInfo = DeviceInfo.current()
        BluetoothResponder.shared.OTACheck(deviceInfo: deviceInfo) { fileINfo in
            
            guard let fileINfo = fileINfo else {
                OTABrageRelay.accept(false)
                return
            }
            
            /// 非空 有升级
            OTABrageRelay.accept(!fileINfo.isEmpty)
            
        } failure: { error in
            
        }

    }
    
}
